import { _decorator, Component, Node, UITransform, Vec3 } from 'cc';
import { EventManager } from './Event/EventManager';
import { GameEventType } from './Event/EnumDefine';
import { DataConfig } from './Config/DataConfig';
const { ccclass, property } = _decorator;

/** 背景滚动 */
@ccclass
export default class BackgroundScroll extends Component {

    @property(Node)
    private background1: Node = null; // 第一个背景图

    @property(Node)
    private background2: Node = null; // 第二个背景图

    private scrollSpeed: number = 100; // 滚动速度

    private backgroundHeight: number = 0; // 背景图的高度

    onLoad(): void {
        this.scrollSpeed = DataConfig.initSpeed;
        EventManager.instance.registerEvent(GameEventType.Change_Roll_Speed, (speed:number)=>{
            this.scrollSpeed = speed;
        }, this);
    }

    start() {
        // 获取背景图的高度
        const uiTransform1 = this.background1.getComponent(UITransform);
        this.backgroundHeight = uiTransform1.height;
    }

    update(dt: number) {
        if(DataConfig.isGameStop){
            return;
        }
        
        // 控制背景图上下滚动
        const pos1 = this.background1.position;
        const pos2 = this.background2.position;

        this.background1.setPosition(pos1.x, pos1.y - this.scrollSpeed * dt);
        this.background2.setPosition(pos2.x, pos2.y - this.scrollSpeed * dt);

        // 当背景图滚动出屏幕时，将其移动到上方
        if (this.background1.position.y <= -this.backgroundHeight) {
            this.background1.setPosition(pos1.x, this.background2.position.y + this.backgroundHeight);
        }

        if (this.background2.position.y <= -this.backgroundHeight) {
            this.background2.setPosition(pos2.x, this.background1.position.y + this.backgroundHeight);
        }
    }
}
